﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Comissoes.Models;
using Comissoes.JQGridObject;
using Comissoes.Utilities;

namespace Comissoes.Controllers
{
    public class TransportadoresController : AppController
    {
        xcontEntities db = new xcontEntities();

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult TransportadoresLookupList()
        {
            return Json((from c in db.TRANSPORTADORES.Include("PESSOAS").ToList() where c.PESSOAS.NOME_PESSOA.ToUpper().Contains(Request["term"].ToUpper()) select new { value = c.PESSOAS.NOME_PESSOA, label = c.PESSOAS.NOME_PESSOA, id = c.COD_TRAN }).Take(10), JsonRequestBehavior.AllowGet);
        }

        // Monta a lista de tipos de produtos
        public JsonResult TransportadoresList(String sidx, String sord, Int32 page, Int32 rows, Boolean _search, String COD_TRAN, String NOME_TRAN, String searchOper)
        {
            var q = from c in db.TRANSPORTADORES
                    select new
                    {
                        c.COD_TRAN,
                        NOME_TRAN = c.PESSOAS.NOME_PESSOA
                    };

            String searchField = string.IsNullOrEmpty(NOME_TRAN) ? "COD_TRAN" : "NOME_TRAN";
            String searchString = string.IsNullOrEmpty(NOME_TRAN) ? COD_TRAN : NOME_TRAN;

            JQGridBuilder jbuilder = new JQGridBuilder(q, page, sidx, sord, searchField, searchString, searchOper, "COD_TRAN", _search, rows);

            return Json(jbuilder.GetObject(), JsonRequestBehavior.AllowGet);
        }

        public ActionResult Details(int id)
        {
            return View(db.TRANSPORTADORES.Include("PESSOAS").FirstOrDefault(t => t.COD_TRAN == id));
        }

        public ActionResult Edit(Int32? id)
        {
            if (id.HasValue)
                return View(new TransportadoresModel(id));
            else
                return View(new TransportadoresModel());
        }

        [HttpPost]
        public ActionResult Edit(Int32? id, FormCollection form)
        {
            TransportadoresModel transportador = new TransportadoresModel(id);

            if (transportador.UpdateValidate(form).Any())
                return Json(transportador.UpdateValidate(form), JsonRequestBehavior.AllowGet);

            else
                transportador.Update(form);

            return Json(transportador.transportador.COD_TRAN, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Delete(Int32 id)
        {
            List<string> erros = new List<string>();
            try
            {
                db.DeleteObject(db.TRANSPORTADORES.FirstOrDefault(t => t.COD_TRAN == id));
                db.SaveChanges();

                return Json(true, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                erros.Add(ex.Message);
                if (ex.InnerException != null)
                    erros.Add(ex.InnerException.Message);
            }

            return Json(erros, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Veiculos(String sidx, String sord, Int32 page, Int32 rows, Boolean _search, String searchField ,String searchString,String searchOper, Int32? COD_TRAN)
        {
            try
            {
                var q = from c in db.VEICULOS
                        where c.TRANSPORTADORES.COD_TRAN == COD_TRAN
                        select new
                        {
                            act = "",
                            c.ID_VEIC,
                            PLACA_VEIC = c.PLACA_VEIC.Substring(0, 3) + " " + c.PLACA_VEIC.Substring(3, 4),
                            c.RNTC_VEIC,
                            c.CIDADES.UFS.SIGLA_UF,
                            c.CIDADES.NOME_CID
                        };

                JQGridBuilder jbuilder = new JQGridBuilder(q.AsQueryable(), page, sidx, sord, searchField, searchString, searchOper, "ID_VEIC", _search, rows);

                return Json(jbuilder.GetObject(), JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult VeiculoUpdate(Int32? COD_TRAN, Int32? id, String NOME_CID, String SIGLA_UF, String PLACA_VEIC, String RNTC_VEIC)
        {
            List<String> erros = new List<string>();

            if (!erros.Any())
            {
                try
                {
                    VEICULOS veiculo = new VEICULOS();
                    
                    if (id.Existe())
                    {
                        veiculo = db.VEICULOS.FirstOrDefault(t => t.ID_VEIC == id);
                    }
                    else
                    {
                        db.AddToVEICULOS(veiculo);
                        veiculo.TRANSPORTADORES = db.TRANSPORTADORES.FirstOrDefault(t => t.COD_TRAN == COD_TRAN);
                    }

                    veiculo.CIDADES = db.CIDADES.FirstOrDefault(t => t.NOME_CID == NOME_CID && t.UFS.SIGLA_UF == SIGLA_UF);
                    veiculo.PLACA_VEIC = PLACA_VEIC.Replace(" ","").ToUpper();
                    veiculo.RNTC_VEIC = RNTC_VEIC;

                    db.SaveChanges();

                    return Json(true, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    erros.Add(ex.Message);
                }
            }

            return Json(erros, JsonRequestBehavior.AllowGet);
        }

        public ActionResult VeiculoDelete(Int32? id)
        {
            List<String> erros = new List<string>();

            if (!erros.Any())
            {
                try
                {
                    db.DeleteObject(db.VEICULOS.FirstOrDefault(t => t.ID_VEIC == id));

                    db.SaveChanges();

                    return Json(true, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    erros.Add(ex.Message);
                }
            }

            return Json(erros, JsonRequestBehavior.AllowGet);
        }
    }
}
